package com.wzh.gulimall.seckill.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.fastjson.JSON;
import com.wzh.common.exception.BizCodeEnume;
import com.wzh.common.utils.R;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SeckillSentinelConfig{
    /**
     * 2.2.0以后的版本实现的是BlockExceptionHandler；以前的版本实现的是WebCallbackManager
     * @param httpServletRequest
     * @param httpServletResponse
     * @param e
     * @throws Exception
     */
    /**
     * 因为版本冲突导致无法引入 WebCallbackManager
     */
    public SeckillSentinelConfig() {
        WebCallbackManager.setUrlBlockHandler((request, response, ex) -> {
            R error = R.error(BizCodeEnume.TOO_MANY_REQUESTS_EXCEPTION.getCode(), BizCodeEnume.TOO_MANY_REQUESTS_EXCEPTION.getMsg());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().write(JSON.toJSONString(error));
        });
    }
}